﻿using MediatR;
using Process.Api.Application.Command;
using Process.BLL;
using Process.DAL;
using Process.Model;
using Process.Infastructure;
using Microsoft.EntityFrameworkCore;

namespace Process.Api.Application.Handler
{
    public class UpdateProcessFlowHandler : IRequestHandler<UpdateProcessFlowCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<ProcessFlow> processFlowRepo;
        private readonly IProcessRepository<FlowProcessRelation> relationRepo;
        private readonly IProcessRepository<Processinfo> processinfoRepo;
        private readonly ProcessDbContext _db;

        public UpdateProcessFlowHandler(IProcessRepository<ProcessFlow> processFlowRepo, IProcessRepository<FlowProcessRelation> relationRepo, IProcessRepository<Processinfo> processinfoRepo, ProcessDbContext db)
        {
            this.processFlowRepo = processFlowRepo;
            this.relationRepo = relationRepo;
            this.processinfoRepo = processinfoRepo;
            this._db = db;
        }
        /// <summary>
        /// 修改工艺流程
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(UpdateProcessFlowCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 验证工艺流程是否存在
                var existingFlow = processFlowRepo.GetAllAsync().FirstOrDefault(x => x.Id == request.Id);
                if (existingFlow == null)
                {
                    result.Message = "工艺流程不存在";
                    return result;
                }

                // 验证工艺流程编号是否重复（排除当前记录）
                var duplicateFlow = processFlowRepo.GetAllAsync().FirstOrDefault(x => x.FlowCode == request.FlowCode && x.Id != request.Id);
                if (duplicateFlow != null)
                {
                    result.Message = "工艺流程编号已存在";
                    return result;
                }

                // 验证工序ID是否存在
                var existingProcessIds = new List<int>();
                foreach (var processId in request.ProcessIds)
                {
                    var process = processinfoRepo.GetAllAsync().FirstOrDefault(x => x.Id == processId);
                    if (process != null)
                    {
                        existingProcessIds.Add(processId);
                    }
                }

                if (existingProcessIds.Count == 0)
                {
                    result.Message = "没有有效的工序";
                    return result;
                }

                // 使用事务确保数据一致性
                await using var tx = await _db.Database.BeginTransactionAsync(cancellationToken);
                try
                {
                    // 更新工艺流程基本信息
                    existingFlow.FlowCode = request.FlowCode;
                    existingFlow.FlowName = request.FlowName;
                    existingFlow.FlowNumber = request.FlowNumber;
                    existingFlow.Responsible = request.Responsible;
                    existingFlow.Department = request.Department;
                    existingFlow.Status = request.Status;
                    existingFlow.Remark = request.Remark;
                    existingFlow.UpdateTime = DateTime.Now;
                    existingFlow.Updater = "系统"; // 这里可以根据实际需求设置

                    await processFlowRepo.UpdateAsync(existingFlow);

                    // 删除原有的工序关系
                    var existingRelations = relationRepo.GetAllAsync().Where(x => x.ProcessFlowId == request.Id).ToList();
                    foreach (var relation in existingRelations)
                    {
                        await relationRepo.DeleteAsync(relation);
                    }

                    // 添加新的工序关系
                    int sort = 1;
                    foreach (var processId in existingProcessIds)
                    {
                        var newRelation = new FlowProcessRelation
                        {
                            ProcessFlowId = request.Id,
                            ProcessId = processId,
                            Sort = sort++,
                            Remark = "无",
                            CreateTime = DateTime.Now,
                            Creater = "系统"
                        };
                        await relationRepo.CreateAsync(newRelation);
                    }

                    await _db.SaveChangesAsync(cancellationToken);
                    await tx.CommitAsync(cancellationToken);

                    result.Data = 1;
                    result.Message = "更新成功";
                }
                catch (Exception ex)
                {
                    await tx.RollbackAsync(cancellationToken);
                    result.Message = "更新失败：" + ex.Message;
                }
            }
            catch (Exception ex)
            {
                result.Message = "更新失败：" + ex.Message;
            }

            return result;
        }
    }
}
